package org.grow.basic.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.grow.basic.dao.ShoppingBillItemMapper;
import org.grow.basic.dao.ShoppingBillMapper;
import org.grow.basic.entity.*;
import org.grow.basic.exception.BillStateException;
import org.grow.basic.exception.CommonException;
import org.grow.basic.service.CodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.awt.*;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @Author: xwg
 * @CreateDate: 2022/5/23
 */
//@CrossOrigin
@RestController
//swimming/shopping/insert
@RequestMapping(value = {"/swimming/shopping","/basic/shopping"})
public class ShoppingBillController {
    public static final String anonymousUser = "anonymousUser";

    @Autowired
    private CodeGenerator codeGenerator;

    @Autowired
    private ShoppingBillMapper shoppingBillMapper;

    @Autowired
    private Point point;

    @PostMapping("/insert")
    public ShoppingBill insert(@RequestBody ShoppingBill shoppingBill) {

//        构建关系
        String sh = codeGenerator.nextCode("SH");
        shoppingBill.setShoppingBillCode(sh);
        for (ShoppingBillItem item : shoppingBill.getShoppingBillItems()) {
            item.setShoppingBillFk(sh);
        }

//        计算属性
        BigDecimal sum = new BigDecimal("0");
        for (ShoppingBillItem item : shoppingBill.getShoppingBillItems()) {
            sum = sum.add(item.getGoodsPrice().multiply(item.getQuantity()));
        }
        System.out.println("后端计算出总计金额：" + sum);
        shoppingBill.setAmount(sum);

//        健壮
        shoppingBill.setSubmitter(SecurityContextHolder.getContext().getAuthentication().getName());
        shoppingBill.setSubmitTime(null);
        shoppingBill.setAuditor(null);
        shoppingBill.setAuditScore(-1);
        shoppingBill.setResubmitTimes(0);
        shoppingBill.setAbandon(false);
        shoppingBill.setUpdateTime(LocalDateTime.now());
        shoppingBill.setShoppingState(ShoppingState.toSubmit);

        int insert = shoppingBillMapper.insert(shoppingBill);
        int items = shoppingBillMapper.insertItems(shoppingBill.getShoppingBillItems());
        return shoppingBill;

    }

    ///swimming/shopping/query4submitter
    @PostMapping("/query4submitter")
    public PagedResult<ShoppingBill> query4submitter(
            @RequestBody ShoppingSubmitQC shoppingSubmitQC) {
        Page<ShoppingBill> page = new Page<>(shoppingSubmitQC.getPageNum(), shoppingSubmitQC.getPageSize());
        System.out.println(page);
        IPage<ShoppingBill> paged = shoppingBillMapper.dynamicSubmit(page, shoppingSubmitQC, SecurityContextHolder.getContext().getAuthentication().getName());

        return new PagedResult<>(paged.getTotal(), paged.getRecords());
    }

    @GetMapping("/shoppingStates")
    public List<StateDto> shoppingStates() {
        ArrayList<StateDto> stateDtos = new ArrayList<>();
        for (ShoppingState state : ShoppingState.values()) {
            stateDtos.add(
                    new StateDto(state.ordinal(), state.name(), state.getLabel()));
        }
        return stateDtos;

    }

    //    swimming/shopping
//    /find/SH16532882265034
    @GetMapping("/find/{code}")
    public ShoppingBill findByCode(@PathVariable String code) {
        System.out.println(code);
        ShoppingBill shoppingBill = shoppingBillMapper.selectDomainById(code);
        System.out.println(shoppingBill);
        return shoppingBill;
    }

    //    /swimming/shopping/submit/SH16532882265034
    @PutMapping("/submit/{code}")
    public ShoppingBill submitByCode(@PathVariable String code) {
        ShoppingBill shoppingBill = shoppingBillMapper.findByCode(code);
        if (shoppingBill == null) {
            throw new CommonException("数据库没有这条数据");
        }

        if (shoppingBill.getShoppingState() != ShoppingState.toSubmit) {
            throw new BillStateException("只有处于待提交状态的单据才能提交");
        }
        shoppingBill.setShoppingState(ShoppingState.toAudit);

        shoppingBill.setSubmitTime(LocalDateTime.now());
        shoppingBill.setUpdateTime(LocalDateTime.now());
        shoppingBillMapper.updateById(shoppingBill);

        return shoppingBill;
    }

    @PostMapping("/query4auditor")
    public PagedResult<ShoppingBill> query4auditor(
            @RequestBody ShoppingAuditQC shoppingAuditQC) {
//        System.out.println(shoppingAuditQC);
        Page<ShoppingBill> billPage = new Page<>(shoppingAuditQC.getPageNum(),
                shoppingAuditQC.getPageSize());
        IPage<ShoppingBill> page = shoppingBillMapper.dynamicAudit(billPage,
                shoppingAuditQC, ShoppingState.toSubmit);
        return new PagedResult<>(page.getTotal(), page.getRecords());
    }

    //    /swimming/shopping/audit
    //    {"shoppingBillCode":"SH16534406710984","auditScore":80}
    @PutMapping("/audit")
    public String audit(@RequestBody ShoppingBillAuditDto shoppingBillAuditDto) {
        System.out.println(shoppingBillAuditDto);
        ShoppingBill bill = shoppingBillMapper.findByCode(shoppingBillAuditDto.getShoppingBillCode());
        if (bill == null) {
            throw new CommonException("待审核单据不存在");
        }

//        审核 待审核 -》 审核通过/审核不通过
        if (bill.getShoppingState() != ShoppingState.toAudit) {
            throw new BillStateException("只有处于待审核状态的单据才能审核");
        }
        if (shoppingBillAuditDto.getAuditScore() < 60) {
            bill.setShoppingState(ShoppingState.refused);
        } else {
            bill.setShoppingState(ShoppingState.agreed);
        }

        bill.setAuditor(SecurityContextHolder.getContext().getAuthentication().getName());
        bill.setAuditScore(shoppingBillAuditDto.getAuditScore());
        bill.setUpdateTime(LocalDateTime.now());
        shoppingBillMapper.updateById(bill);
        return "ok";

    }

    @Autowired
    private ShoppingBillItemMapper shoppingBillItemMapper;

    @PutMapping("/modify")
    public ShoppingBill modify(@RequestBody ShoppingBill shoppingBill) {

        List<ShoppingBillItem> shoppingBillItems = shoppingBill.getShoppingBillItems();
//        构建关系
        for (ShoppingBillItem shoppingBillItem : shoppingBillItems) {
            shoppingBillItem.setShoppingBillFk(shoppingBill.getShoppingBillCode());
        }
//        计算属性
        BigDecimal sum = new BigDecimal("0");
        for (ShoppingBillItem shoppingBillItem : shoppingBillItems) {
            sum = sum.add(shoppingBillItem.getGoodsPrice().multiply(shoppingBillItem.getQuantity()));
        }
        shoppingBill.setAmount(sum);
//          状态转变  待提交转待提交
        if (shoppingBill.getShoppingState() != ShoppingState.toSubmit) {
            throw new BillStateException("只有处于待提交状态的单据才能修改");
        }
        shoppingBill.setShoppingState(ShoppingState.toSubmit);
        shoppingBill.setUpdateTime(LocalDateTime.now());
//        保存主表
        int i = shoppingBillMapper.updateById(shoppingBill);
//        把该code下所有子表信息删除
        int j = shoppingBillItemMapper.deleteByFk(shoppingBill.getShoppingBillCode());
        int k = shoppingBillItemMapper.batchInsert(shoppingBillItems);

        return shoppingBillMapper.selectDomainById(shoppingBill.getShoppingBillCode());

    }

    //    swimming/shopping/resubmit/SH16532882265034
    @PutMapping("/resubmit/{code}")
    public Boolean resubmit(@PathVariable String code) {
        ShoppingBill bill = shoppingBillMapper.findByCode(code);
        if (bill == null) {
            throw new CommonException("单据不存在");
        }

//        重交 ： 待审核状态 转 待提交状态
        if (bill.getShoppingState() != ShoppingState.toAudit) {
            throw new BillStateException("只有处于待审核状态的单据才能重交");
        }
        bill.setShoppingState(ShoppingState.toSubmit);

        bill.setResubmitTimes(bill.getResubmitTimes() + 1);
        bill.setUpdateTime(LocalDateTime.now());
        int i = shoppingBillMapper.updateById(bill);
        return i == 1;

    }

}
